import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import { resolve } from "path";
import vueSetupExtend from "vite-plugin-vue-setup-extend";
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
import {
  createStyleImportPlugin,
  VxeTableResolve,
} from "vite-plugin-style-import";
import topLevelAwait from "vite-plugin-top-level-await";
import viteCompression from "vite-plugin-compression";
import { templateCompilerOptions } from "@tresjs/core";

const pathResolve = (dir: string) => {
  return resolve(__dirname, ".", dir);
};
const alias: Record<string, string> = {
  "/@": pathResolve("./src/"),
  "vue-i18n": "vue-i18n/dist/vue-i18n.cjs.js",
};
export default defineConfig({
  resolve: { alias },
  plugins: [
    vue({
      ...templateCompilerOptions,
    }),
    vueSetupExtend(), // setup语法糖增强插件
    AutoImport({
      imports: ["vue", "vue-router", "pinia"], // 自动导入的依赖库数组
      dts: "./auto-imports.d.ts", // 自动导入类型定义文件路径
    }),
    Components({
      resolvers: [ElementPlusResolver()],
    }),
    createStyleImportPlugin({
      resolves: [VxeTableResolve()], // 配置vxetable 按需加载
    }),
    topLevelAwait({
      promiseExportName: "__tla", // TLA Promise 变量名
      promiseImportName: (i) => `__tla_${i}`, // TLA Promise 导入名
    }),
    viteCompression({
      verbose: true,
      algorithm: "gzip",
      threshold: 1024 * 10,
      deleteOriginFile: false, // 压缩后删除原来的文件
    }),
  ],
  server: {
    host: "0.0.0.0", // 服务器地址
    port: 7300, // 服务器端口号
    open: true, // 是否自动打开浏览器
    hmr: true, // 启用热更新
    proxy: {
      "/api": {
        target: "http://lovezengcheng.top",
        ws: true, // 是否启用 WebSocket
        changeOrigin: true, // 是否修改请求头中的 Origin 字段
        rewrite: (path) => path.replace(/^\/api/, "/api"),
      },
    },
  },
  base: "./", // 打包基础路径
  build: {
    outDir: "dist", // 打包输出目录
    chunkSizeWarningLimit: 1500, // 代码分包阈值
    rollupOptions: {
      output: {
        entryFileNames: `assets/[name].[hash].js`,
        chunkFileNames: `assets/[name].[hash].js`,
        assetFileNames: `assets/[name].[hash].[ext]`,
        compact: true,
        manualChunks: {
          vue: ["vue", "vue-router", "pinia"],
        },
      },
    },
  },
});
